package com.item.yxlottery.yxlottery.callback;

/*
 *------------------------------
 * @创建者      Administrator
 * @创建时间    2016/12/19 21:23
 * @文件描述    filecallback
 *------------------------------
 */

import android.content.Context;

import com.blankj.utilcode.utils.AppUtils;
import com.item.yxlottery.yxlottery.views.ApkLoadingDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class MyApkFileCallBack extends FileCallBack {

    private Context mContext;
    private boolean mIsShowLoading = false;
    private String mDestFileDir;//目标文件存储的文件夹路径
    private String mDestFileName;//目标文件存储的文件名
    private ApkLoadingDialog mApkLoadingDialog;

    public MyApkFileCallBack(String destFileDir, String destFileName) {
        super(destFileDir, destFileName);
    }

    public MyApkFileCallBack(Context context, boolean isShowLoading, String destFileDir, String destFileName) {
        super(destFileDir, destFileName);
        mContext = context;
        mIsShowLoading = isShowLoading;
        mDestFileDir = destFileDir;
        mDestFileName = destFileName;
    }

    @Override
    public void onBefore(Request request, int id) {
        super.onBefore(request, id);
        if (mIsShowLoading) {
            mApkLoadingDialog = new ApkLoadingDialog(mContext);
        }
    }

    @Override
    public void onError(Call call, Exception e, int id) {

    }

    @Override
    public void onResponse(File response, int id) {

    }

    @Override
    public void inProgress(float progress, long total, int id) {
        super.inProgress(progress, total, id);
        mApkLoadingDialog.setMaxProgress(total);
        mApkLoadingDialog.setProgress(progress);
        mApkLoadingDialog.show();
    }

    @Override
    public void onAfter(int id) {
        super.onAfter(id);
        if (mIsShowLoading) {
            mApkLoadingDialog.dismiss();
            if (mDestFileName.endsWith("apk")) {
                AppUtils.installAppSilent(mContext, mDestFileDir + "/" + mDestFileName);
            }
        }
    }

    @Override
    public File parseNetworkResponse(Response response, int id) throws Exception {
        return saveFile(response, id);
    }

    public File saveFile(Response response, final int id) throws IOException {
        InputStream is = null;
        byte[] buf = new byte[2048];
        int len = 0;
        FileOutputStream fos = null;
        try {
            is = response.body().byteStream();
            final long total = response.body().contentLength();
            long sum = 0;
            File dir = new File(mDestFileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, mDestFileName);
            fos = new FileOutputStream(file);
            while ((len = is.read(buf)) != -1) {
                sum += len;
                fos.write(buf, 0, len);
                final long finalSum = sum;
                OkHttpUtils.getInstance().getDelivery().execute(new Runnable() {
                    @Override
                    public void run() {

                        inProgress(finalSum * 1.0f / total, total, id);
                    }
                });
            }
            fos.flush();
            return file;
        } finally {
            try {
                response.body().close();
                if (is != null)
                    is.close();
            } catch (IOException e) {
            }
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
            }
        }
    }
}
